package webserver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import platform.service.SerMgrThread;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class HTMLMaker {
    private static HTMLMaker instance;

    private HTMLMaker() {}

    public static HTMLMaker getInstance() {
        // 第一次检查instance是否被实例化出来，如果没有进入if块
        if (instance == null) {
            synchronized (HTMLMaker.class) {
                // 某个线程取得了类锁，实例化对象前第二次检查instance是否已经被实例化出来，如果没有，才最终实例出对象
                if (instance == null) {
                    instance = new HTMLMaker();
                }
            }
        }
        return instance;
    }

    public String makeTable(String header, String jsonArrStrData) {
        Map<String, Object> headerMap = new LinkedHashMap<>();
        try {
            headerMap = JSON.parseObject(header);
        } catch (Exception e) {
            JSONArray jsonArray = JSON.parseArray(header);
            for (int i = 0; i < jsonArray.size(); i++) {
                headerMap.put(jsonArray.getString(i), jsonArray.getString(i));
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\" class=\"beautiful-table\">\n");
        sb.append("  <tr>\n");
        sb.append("    <th></th>\n");
        for (Object value : headerMap.values()) {
            sb.append("    <th>").append(value).append("</th>\n");
        }
        sb.append("  </tr>\n");
        try {
            JSONArray jsonArr = JSONArray.parseArray(jsonArrStrData);
            for (int i = 0; i < jsonArr.size(); i++) {
                JSONObject jsonObj = jsonArr.getJSONObject(i);
                sb.append("  <tr>\n");
                sb.append("    <td>").append(i + 1).append("</td>\n");
                for (String key : headerMap.keySet()) {
                    Object value = jsonObj.get(key);
                    if (value == null) {
                        value = "";
                    }
                    sb.append("    <td class = \"").append(value).append("\">").append(value).append("</td>\n");
                }
                sb.append("  </tr>\n");
            }
        } catch (Exception ignored) {}
        sb.append("</table>\n");
        return sb.substring(0, sb.length() - 1);
    }
}
